package com.lfc.myframe.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.provider.Settings
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.CallSuper
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.viewbinding.ViewBinding
import com.gyf.immersionbar.ImmersionBar
import com.lfc.myframe.R
import com.lfc.myframe.event.EBParams
import com.lfc.myframe.event.EBParams.EB_BackHome
import com.lfc.myframe.event.EBParams.EB_ExitLogin
import com.lfc.myframe.event.EBParams.EB_LoginSuccess
import com.lfc.myframe.event.EBParams.EB_NetConnectState
import com.lfc.myframe.event.EBParams.EB_NetFailed2Main
import com.lfc.myframe.event.EBParams.EB_ResetPW
import com.lfc.myframe.event.LoginResultEvent
import com.lfc.myframe.share.MMKVHub
import com.lfc.myframe.share.Params
import com.lfc.myframe.ui.MainActivity
import com.lfc.myframe.ui.login.LoginA
import com.lfc.myframe.utils.*
import com.lfc.myframe.utils.network.NetChangeObserver
import com.lfc.myframe.utils.network.NetStateReceiver
import com.lfc.myframe.utils.network.NetUtils
import com.lfc.myframe.widget.WaitDialog
import com.lfc.myframe.widget.alerterTop.Alerter
import com.mdchina.juhai.utils.ToastUtils
import com.mdchina.juhai.utils.ToastUtils.Companion.hideToask
import com.mdchina.thelifeorder.share.MessageEvent
import com.scwang.smart.refresh.footer.BallPulseFooter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxDeviceTool
import com.tamsiree.rxkit.TLog
import com.trello.rxlifecycle2.LifecycleProvider
import com.trello.rxlifecycle2.LifecycleTransformer
import com.trello.rxlifecycle2.RxLifecycle
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.android.RxLifecycleAndroid
import io.reactivex.subjects.BehaviorSubject
import kotlinx.android.synthetic.main.activity_base.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.text.SimpleDateFormat
import java.util.*
import io.reactivex.Observable

abstract class BaseA<VB : ViewBinding> : AppCompatActivity(), View.OnClickListener,
    LifecycleProvider<ActivityEvent> {

    /**
     * ViewBinding
     */
    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    /**
     * 上下文context
     */
    var baseContext: Activity = FragmentActivity()
    var baseCtx: FragmentActivity = FragmentActivity()

    /**
     * 开始请求
     */
    open fun ReGetData() {}

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    /**
     * 是否需要显示 TipView
     */
    open fun enableNetworkTip(): Boolean = true

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        ReGetData()
    }


    var mImmersionBar: ImmersionBar? = null
    private var imm: InputMethodManager? = null
    private var mWaitDialog: WaitDialog? = null
    var mClassicsHeader: ClassicsHeader? = null

    //    public ClassicsFooter mClassicsFooter;
    var mClassicsFooter: BallPulseFooter? = null

    /**
     * 分页加载页数
     */
    var pageNum = 1

    @CallSuper
    override fun onCreate(savedInstanceState: Bundle?) {
//        this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        RxDeviceTool.setPortrait(this)
        super.onCreate(savedInstanceState)
        _binding = bindingInflater.invoke(layoutInflater)
        super.setContentView(R.layout.activity_base)
        RxActivityTool.addActivity(this)
        setSupportActionBar(toolbar)
//        if ()
        baseContext = this@BaseA
        lifecycleSubject.onNext(ActivityEvent.CREATE)
        initMVP()
        initView()
        initConfig()

    }

    private fun initView() {
        initToolBar()
        initImmerBar()
        img_base_back.setOnClickListener { finish() }
        initSmartRefresh()
        initSmartRefreshValue()
    }

    /**
     *  initView
     */
    open fun initMVP() {}

    /**
     *  初始化 状态栏设置
     *  isdark  true  设置状态栏 字体黑色  false  白色
     */
    public fun initImmerBar(isDark: Boolean = true, isSet: Boolean = true) {
        try {
            var currentCls = RxActivityTool.currentActivity()
            if (!isSet) return
        } catch (e: Exception) {
            e.printStackTrace()
        }

        mImmersionBar = ImmersionBar.with(this)
        mImmersionBar?.titleBar(toolbar)?.statusBarDarkFont(isDark, 0.2f)?.init()
    }

    fun initImmKeybord() {
        mImmersionBar?.keyboardEnable(true)?.init()
    }


    override fun setContentView(view: View) {
//        if (rootLayout == null)
//            return
//        rootLayout.addView(
//            view,
//            ViewGroup.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.MATCH_PARENT
//            )
//        )
        val ivLeftLayoutParams: ConstraintLayout.LayoutParams = ConstraintLayout.LayoutParams(-1, 0)
        ivLeftLayoutParams.topToBottom = R.id.lay_appbar
        ivLeftLayoutParams.leftToLeft = R.id.lay_root_base
        ivLeftLayoutParams.bottomToBottom = R.id.lay_root_base
        view.layoutParams = ivLeftLayoutParams
        lay_root_base.addView(view)


    }

    override fun setContentView(layoutId: Int) {
        setContentView(View.inflate(this, layoutId, null))

    }

    fun setContentView(layoutId: Int, isAddParent: Boolean = true) {
        if (isAddParent)
            setContentView(View.inflate(this, layoutId, null))
        else super.setContentView(layoutId)

    }

    override fun onClick(v: View?) {}

    open fun DoClick(v: View) {}

    private fun initToolBar() {
        setSupportActionBar(toolbar)
        val actionBar = supportActionBar
        if (actionBar != null) actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
//        img_base_back.setOnClickListener(this)

    }

    /**
     * 设置标题栏是否显示
     */
    fun SetToolBarVisiabale(isShow: Boolean) {
        lay_appbar?.visibility = View.VISIBLE
        lay_appbar?.visibility = View.GONE
        lay_appbar?.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    /**
     * strTitle 标题
     * strRight1  右侧按钮
     */
    fun initTitle(strTitle: String?, strRight1: String? = "") {
        tv_base_title.text = strTitle
        if (!TextUtils.isEmpty(strRight1)) {
            tv_base_right.visibility = View.VISIBLE
            tv_base_right.setText(strRight1)
        } else tv_base_right.visibility = View.GONE
    }


    private fun initConfig() {
        //订阅EventBus这个必须写
        if (useEventBus())
            EventBus.getDefault().register(this)
        initNetWork()
    }

    private fun initNetWork() {

        //开启广播去监听 网络 改变事件
        NetStateReceiver.registerObserver(object : NetChangeObserver {
            override fun onNetConnected(type: NetUtils.NetType?) {
                if (type != null) {
//                    onNetworkConnected(type)
                    EventBus.getDefault()
                        .post(
                            MessageEvent(
                                EBParams.EB_NetConnectState,
                                typeValue = 1,
                                value01 = type.name.toString()
                            )
                        )

                }
            }

            override fun onNetDisConnect() {
//                onNetworkDisConnected()
                EventBus.getDefault()
                    .post(MessageEvent(EBParams.EB_NetConnectState, typeValue = 0))

            }
        })

    }

    /**
     *  判断网络状态
     *
     */
    private fun checkNetwork(isConnected: Boolean) {
        try {
            if (enableNetworkTip()) {
                if (isConnected) {
                    var hasNetwork = PreferencesUtils.getBoolean(this, Params.HAS_NETWORK_KEY)
                    if (hasNetwork != isConnected)
                        doReConnected()
                    if (!Alerter.isShowing()) {
                        Alerter.hide()
                    }
                } else {
                    ShowTopAlaret()
                }
            } else {
                var currentCls = RxActivityTool.currentActivity()
                when (currentCls) {
//                     首页 欢迎页  广告业 不显示这个弹框
                    LoginA::class.java -> {
                        if (useEventBus())
                            EventBus.getDefault()
                                .postSticky(MessageEvent(name = EB_NetFailed2Main, typeValue = 1))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            if (!Alerter.isShowing()) {
                Alerter.hide()
            }
        } finally {
            PreferencesUtils.putBoolean(baseContext, Params.HAS_NETWORK_KEY, isConnected)


        }

    }

    open fun ShowTopAlaret() {
        RxActivityTool.currentActivity()?.let {
            Alerter.create(it).setTitle("提示")
                .setText("当前网络异常，请您检查网络设置").setIcon(R.drawable.alerter_ic_notifications_svg)
                .setBackgroundColorRes(R.color.prompt_warning).setDuration(5 * 1000)
                .enableSwipeToDismiss().setOnClickListener {
                    val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
                    startActivity(intent)
                    Alerter.hide()
                }.setOnHideListener {
                    //    TODO("这个地方需要注意,enableSwipeToDismiss 不触发这回调！ ")
                    LgU.d("弹框 藏起来了")
                    if (useEventBus())
                        EventBus.getDefault()
                            .post(MessageEvent(name = EB_NetFailed2Main, typeValue = 2))

                }?.show()
        }
    }


    /**
     * 扩展 吐司
     */
    fun Context.showToast(strMsg: String?) {
        if (strMsg.isNullOrBlank()) return

        ToastUtils.showToask(baseContext, strMsg)


    }

    /**
     * 扩展 吐司
     */
    fun Context.showToastLong(strMsg: String?) {
        if (strMsg.isNullOrBlank()) return
        ToastUtils.showLongToask(baseContext, strMsg)


    }

    private var mActivityJumpTag: String? = null
    private var mActivityJumpTime: Long = 0

    /**
     * 检查当前 Activity 是否重复跳转了，不需要检查则重写此方法并返回 true 即可
     *
     * @param intent 用于跳转的 Intent 对象
     * @return 检查通过返回true, 检查不通过返回false
     */
    protected fun startActivitySelfCheck(intent: Intent): Boolean {
        // 默认检查通过
        var result = true
        // 标记对象
        val tag: String?
        if (intent.getComponent() != null) { // 显式跳转
            tag = intent.getComponent()!!.getClassName()
        } else if (intent.getAction() != null) { // 隐式跳转
            tag = intent.getAction()
        } else {
            return result
        }

        if (tag == mActivityJumpTag && mActivityJumpTime >= SystemClock.uptimeMillis() - 1000) {
            // 检查不通过
            result = false
        }

        // 记录启动标记和时间
        mActivityJumpTag = tag
        mActivityJumpTime = SystemClock.uptimeMillis()
        return result
    }

    override fun finish() {
        super.finish()
        hideSoftKeyBoard()
    }

    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (this.imm == null) {
            this.imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && this.imm != null) {
            this.imm?.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

    /**
     * 动态隐藏软键盘
     *
     * @param context 上下文
     * @param edit    输入框
     */
    fun hideSoftInput(context: Context, edit: EditText) {
        edit.clearFocus()
        val inputmanger =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputmanger.hideSoftInputFromWindow(edit.windowToken, 0)
    }

    @Subscribe(sticky = true)
    //    @Subscribe(threadMode = ThreadMode.MAIN)
    //    @Subscribe(threadMode = ThreadMode.POSTING)
    open fun onEventBus(message: MessageEvent) {
        // 在这里已经接收到消息 我加判断是为了实现群发单实现的效果
        val str_name = message.name
        LgU.d("收到 回调消息" + str_name + "  " + message.type)
        if (TextUtils.isEmpty(str_name)) {
            return
        }

        /* */
        /**
         * 我真他妈的是一个小精灵鬼！
         */
        val cla = javaClass

        if (TextUtils.equals(str_name, EB_ExitLogin)) {
            LgU.d("当前activity ：$cla")
            if (cla == MainActivity::class.java || cla == LoginA::class.java) {
            } else {
                finish()
            }
        } else if (TextUtils.equals(str_name, EB_ResetPW)) {
            LgU.d("当前activity ：$cla")
            if (cla == MainActivity::class.java || cla == LoginA::class.java) {
            } else {
                finish()
            }
        } else if (TextUtils.equals(str_name, EB_LoginSuccess)) {
            LgU.d("当前activity ：$cla")
//            if (cla == LoginA::class.java || cla == RegisterFirstA::class.java || cla == RegisterSecondA::class.java || cla == RegisterThirdA::class.java) {
            if (cla == LoginA::class.java) {
                finish()
            }
        } else if (TextUtils.equals(str_name, EB_BackHome)) {
            LgU.d("当前activity ：$cla")
            if (cla == MainActivity::class.java) {
            } else {
                finish()
            }
        } else if (TextUtils.equals(str_name, EB_NetConnectState)) {
            if (message.type == 1) {
                TLog.e("有网了！ ${message.password01}")
                checkNetwork(true)
            } else {
                TLog.e("断网了！ ")
                checkNetwork(false)
            }

        }
    }


    /**
     * *  退出登录
     */
    fun ExitLoginSet() {
//        EMClient.getInstance().logout(true);
        initShareSDK()
        MMKVUtil.clearLoginInfo()
//        RongIM.getInstance().disconnect()
//        RongIM.getInstance().logout()
        ExitJpush()
        ClearUserInfo()
        if (useEventBus()) {
            EventBus.getDefault().post(MessageEvent(name = EBParams.EB_ExitLogin))
            EventBus.getDefault().post(LoginResultEvent(type = 2))

        }
    }

    private fun ClearUserInfo() {
        PreferencesUtils.resetuserinfo(baseContext)
        MMKVUtil.removeKey(MMKVHub.KEY_USERTOKEN)
        MMKVUtil.removeKey(MMKVHub.KEY_USERINFO)
    }

    /**
     * 取消授权
     */
    private fun initShareSDK() {
        /*   var qq = ShareSDK.getPlatform(QQ.NAME);
           if (qq != null && qq.isAuthValid()) {
               qq.removeAccount(true);
           }

           var wx = ShareSDK.getPlatform(Wechat.NAME);
           if (wx != null && wx.isAuthValid()) {
               wx.removeAccount(true);
           }*/
    }


    @CallSuper
    override fun onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY)
        super.onDestroy()
        if (useEventBus())
            EventBus.getDefault().unregister(this)
        RxActivityTool.removeActivity(this)
        hideToask()
        _binding = null

    }

    override fun startActivityForResult(intent: Intent?, requestCode: Int) {
        if (startActivitySelfCheck(intent!!)) {
            // 查看源码得知 startActivity 最终也会调用 startActivityForResult
            super.startActivityForResult(intent, requestCode)
        }
    }

    //
    fun showDialog(
        isCancle: Boolean = true,
        strMsg: String? = resources.getString(R.string.loadingmess)
    ) {
        if (mWaitDialog == null) {
            mWaitDialog = WaitDialog.setDialog(
                baseContext,
                if (TextUtils.isEmpty(strMsg)) resources.getString(R.string.loadingmess) else strMsg,
                null
            )
        }
        mWaitDialog?.setCancelable(isCancle)
        mWaitDialog?.show()
    }

    fun hideDialog() {
        if (mWaitDialog != null && mWaitDialog?.isShowing()!!) {

            /**
             * 总感觉这个网络框架  加载框 结束的早了
             * 为了避免 弹框结束 到页面显示成功的 真空期
             * 暂时采用 延时取消的方式处理
             */
            Handler().postDelayed({ mWaitDialog?.dismiss() }, (200 * 1).toLong())


        }
    }

    private fun initSmartRefresh() {

        mClassicsHeader = ClassicsHeader(baseContext)
        //        mClassicsFooter = new ClassicsFooter(baseContext);
        mClassicsFooter = BallPulseFooter(baseContext)
        val deta = Random().nextInt(7 * 24 * 60 * 60 * 1000)
        mClassicsHeader?.setLastUpdateTime(Date(System.currentTimeMillis() - deta))
        mClassicsHeader?.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader?.setTimeFormat(DynamicTimeFormat("更新于 %s"))
        mClassicsHeader?.setEnableLastTime(false)
        mClassicsHeader?.spinnerStyle = SpinnerStyle.Translate
        //        mClassicsHeader.setAccentColor(getResources().getColor(R.color.base_text));//设置强调颜色
        mClassicsHeader?.setPrimaryColor(
            ContextCompat.getColor(
                baseContext,
                R.color.StatusColor0
            )
        )//设置主题颜色

        mClassicsFooter?.setAnimatingColor(
            ContextCompat.getColor(
                baseContext,
                R.color.StatusColor0
            )
        )//设置
        mClassicsFooter?.setNormalColor(
            ContextCompat.getColor(
                baseContext,
                R.color.base_text
            )
        )//设置 颜色


    }

    private fun initSmartRefreshValue() {
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.srl_header_pulling);//"下拉可以刷新";
        ClassicsHeader.REFRESH_HEADER_REFRESHING =
            getString(R.string.srl_header_refreshing);//"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.srl_header_loading);//"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.srl_header_release);//"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.srl_header_finish);//"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.srl_header_failed);//"刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"上次更新 M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"'Last update' M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_SECONDARY =
            getString(R.string.srl_header_secondary);//"释放进入二楼"

        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.srl_footer_pulling);//"上拉加载更多";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.srl_footer_release);//"释放立即加载";
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.srl_footer_loading);//"正在刷新...";
        ClassicsFooter.REFRESH_FOOTER_REFRESHING =
            getString(R.string.srl_footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.srl_footer_finish);//"加载完成";
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.srl_footer_failed);//"加载失败";
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.srl_footer_nothing);//"全部加载完成";

    }


    /**
     * 加载中
     */
    fun show_Loading() {
        LoadingUtil.showLoading(baseContext, "加载中...")
//        showDialog()
    }

    /**
     * 取消加载
     */
    fun hide_Loading() {
        LoadingUtil.dismissLoading()
//        hideDialog()
    }

    @CallSuper
    override fun onStart() {
        super.onStart()
        lifecycleSubject.onNext(ActivityEvent.START)
    }

    @CallSuper
    override fun onResume() {

        super.onResume()
        lifecycleSubject.onNext(ActivityEvent.RESUME)
    }

    @CallSuper
    override fun onPause() {

        lifecycleSubject.onNext(ActivityEvent.PAUSE)
        super.onPause()
    }

    @CallSuper
    override fun onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP)
        super.onStop()
    }

    private val lifecycleSubject = BehaviorSubject.create<ActivityEvent>()

    override fun lifecycle(): Observable<ActivityEvent> {
        return lifecycleSubject.hide()
    }

    override fun <T : Any?> bindUntilEvent(event: ActivityEvent): LifecycleTransformer<T> {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event)
    }

    override fun <T : Any?> bindToLifecycle(): LifecycleTransformer<T> {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject)
    }

    /**
     * 推送设置
     *
     * @param showtype 1 正常注册 2 退出注册
     */
    fun ExitJpush() {
        initJpushNologin()
    }

    fun initJpushNologin() {
        //设置别名（先注册）
//        JPushInterface.setAlias(baseContext, -1, "")

//        val tagSet = LinkedHashSet<String>()
//        var strTagValue = getLanguageTag()
//        tagSet.add(strTagValue)
//        JPushInterface.setTags(baseContext, 10086, tagSet)
    }

}


